<?php


namespace app\common\dao;


use app\common\model\Report as ReportModel;
use app\common\service\PaginateService;
use think\db\Query;

class ReportDao
{
    public static function getQuery($data = [])
    {
        return ReportModel::where(function (Query $query) use ($data) {
            $name = !empty($data['name']) ? trim($data['name']) : "";
            $phone = !empty($data['phone']) ? trim($data['phone']) : "";
            $start_create_time = $data['start_create_time'] ?? "";
            $end_create_time = $data['end_create_time'] ?? "";
            $source_type = $data['source_type'] ?? "";

            if ($name) $query->where('name', 'like', "%$name%");
            if ($phone) $query->where('phone', 'like', "%$phone%");
            if (!empty($start_create_time) && !empty($end_create_time)) $query->whereBetween('create_time', [
                $start_create_time . ' 00:00:00',
                $end_create_time . ' 23:59:59',
            ]);
            if (!empty($source_type)) $query->where('source_type', $source_type);
        });
    }

    public static function getList($data, $appendExtendText = false)
    {
        $limit = !empty($data['limit']) ? $data['limit'] : PaginateService::LIMIT_DEFAULT;
        $list = self::getQuery($data)->order('id', 'DESC')->paginate($limit);
        if ($appendExtendText) $list->getCollection()->map(function ($list) {
            return self::appendExtendText($list);
        });
        PaginateService::appendBackstageResponseData($list);
        return $list;
    }

    public static function appendExtendText(ReportModel $report)
    {
        $report->source_type_text = ReportModel::getSourceTextText($report->source_type);
        return $report;
    }

    /**
     * 创建或新增举报信息
     * @param $data
     * @return bool
     */
    public static function createOrUpdate($data)
    {
        $id = $data['id'] ?? '';
        $name = $data['name'] ?? "";
        $phone = $data['phone'] ?? "";
        $staff_id = $data['staff_id'] ?? "";
        $chat_id = $data['chat_id'] ?? "";
        $source_type = $data['source_type'] ?? "";

        if (!empty($id)) $reportModel = ReportModel::find($id);
        if (empty($id)) $reportModel = new ReportModel();
        $reportModel->name = $name;
        $reportModel->phone = $phone;
        $reportModel->staff_id = $staff_id;
        $reportModel->chat_id = $chat_id;
        $reportModel->source_type = $source_type;
        return $reportModel->save();
    }
}